/**
 * v-copy
 * 复制某个值至剪贴板
 * 接收参数：string类型/Ref<string>类型/Reactive<string>类型
 */
import type { Directive, DirectiveBinding } from 'vue';

import { ElMessage } from 'hive-plus';

interface ElType extends HTMLElement {
  copyData: string | number;
  _handler_: any;
}

export const copy: Directive = {
  mounted(el: ElType, binding: DirectiveBinding) {
    el.copyData = binding.value;
    el._handler_ = () => {
      // 1. 值为空时提示
      if (!el.copyData) {
        ElMessage.warning('复制内容为空');
        return;
      }
      /*
       * 2. 利用textarea标签实现copy
       * 创建一个textarea，然后将textarea设为readonly，防止ios下自动换气键盘，最后将textarea移出可视区
       */
      const textarea: any = document.createElement('textarea');
      textarea.readonly = 'readonly';
      textarea.style.position = 'absolute';
      textarea.style.left = '-9999px';

      // 将要copy的值赋给textarea的value属性
      textarea.value = el.copyData;
      // 将textarea 插入到body中
      document.body.appendChild(textarea);

      /**
       * 实现选中并复制
       * 利用select选中，
       * 利用execCommand命令copy选中的内容到剪贴板中
       */
      textarea.select();
      textarea.setSelectionRange(0, textarea.value.length);
      const result = document.execCommand('Copy');
      if (result) {
        ElMessage.success('复制成功');
      }

      /**
       * 移出textarea
       */
      document.body.removeChild(textarea);
    };

    el.addEventListener('click', el._handler_);
  },
  updated(el: ElType, binding: DirectiveBinding) {
    el.copyData = binding.value;
  },
  beforeUnmount(el: ElType) {
    el.removeEventListener('click', el._handler_);
  },
};
